﻿using System;
using System.Diagnostics.Contracts;
using System.Linq;
using UnitOfWork.Interfaces;

namespace UnitOfWork.EntityFramework
{
	/// <summary>
	/// Оборачивает единицу работы, добавляя действие, вызываемое сразу после освобождения объекта (после Dispose)
	/// </summary>
	public class UnitOfWorkDisposeDecorator : IUnitOfWork
	{
		public UnitOfWorkDisposeDecorator(IUnitOfWork uow, Action action)
		{
			Contract.Requires(uow != null);
			Contract.Requires(action != null);

			_uow = uow;
			_action = action;
		}

		public void Dispose()
		{
			_uow.Dispose();
			_action();
		}

		public IQueryable<TEntity> Query<TEntity>() where TEntity : class
		{
			return _uow.Query<TEntity>();
		}
		public void RegisterNew<TEntity>(TEntity entity) where TEntity : class
		{
			_uow.RegisterNew(entity);
		}
		public void RegisterUnchanged<TEntity>(TEntity entity) where TEntity : class
		{
			_uow.RegisterUnchanged(entity);
		}
		public void RegisterChanged<TEntity>(TEntity entity) where TEntity : class
		{
			_uow.RegisterChanged(entity);
		}
		public void RegisterDeleted<TEntity>(TEntity entity) where TEntity : class
		{
			_uow.RegisterDeleted(entity);
		}
		public void Save()
		{
			_uow.Save();
		}

		private readonly IUnitOfWork _uow;
		private readonly Action _action;
	}
}